package edu.scau.web.system;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import edu.scau.core.constants.AjaxResult;
import edu.scau.system.domain.User; // 确保导入 User 类
import edu.scau.system.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户管理相关接口")
public class UserController {
    @Autowired
    private IUserService userService;

    @GetMapping("/page")
    @Operation(
            summary = "分页查找用户",
            description = "分页查找用户信息,访问权限:ALL",
            parameters = {
                    @Parameter(name = "pageNum", description = "页码", required = true, schema = @Schema(type = "int")),
                    @Parameter(name = "pageSize", description = "每页数据条数", required = true, schema = @Schema(type = "int"))
            },
            requestBody = @RequestBody(
                    description = "用户查询条件",
                    required = false,
                    content = @Content(
                            mediaType = "application/json",
                            schema = @Schema(implementation = User.class)
                    )
            ),
            responses = {
                    @ApiResponse(responseCode = "200", description = "成功", content = @Content(mediaType = "application/json", schema = @Schema(implementation = PageInfo.class))),
                    @ApiResponse(responseCode = "500", description = "错误", content = @Content(mediaType = "application/json", schema = @Schema(implementation = HttpStatus.class)))
            }
    )
    public AjaxResult page(
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("pageSize") Integer pageSize,
            User user
    ) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> list = userService.selectUserList(user);
        PageInfo<User> pageInfo = new PageInfo<>(list);
        return AjaxResult.success(pageInfo);
    }

    @GetMapping("findUserByID/{userId}")
    @Operation(summary = "根据ID获取用户", description = "根据用户ID获取用户信息,访问权限:ALL")
    public AjaxResult getById(@PathVariable("userId") Long userId) {
        return AjaxResult.success(userService.selectUserById(userId));
    }

    @PreAuthorize("hasAuthority('admin')")
    @PostMapping("/insertUser")
    @Operation(summary = "新增用户", description = "新增用户信息,访问权限:admin")
    public AjaxResult add(@org.springframework.web.bind.annotation.RequestBody User user) {
        int count = userService.insertUser(user);
        return count > 0 ? AjaxResult.success("添加用户成功") : AjaxResult.error("用户已经存在");
    }

    @PreAuthorize("hasAuthority('admin')")
    @PutMapping("/updateUser")
    @Operation(summary = "更新用户", description = "更新用户信息,userID是必要字段,访问权限:admin,注意用户名字段为必须")
    public AjaxResult edit(@org.springframework.web.bind.annotation.RequestBody User user) {
        int count = userService.updateUser(user);
        return count > 0 ? AjaxResult.success("更新用户成功") : AjaxResult.error("用户不存在");
    }

    @PreAuthorize("hasAuthority('admin')")
    @DeleteMapping("/delete/{userId}")
    @Operation(summary = "根据ID删除用户", description = "根据用户ID删除用户信息,访问权限:admin")
    public AjaxResult deleteById(@PathVariable Long userId) {
        int count = userService.deleteUserById(userId);
        return count > 0 ? AjaxResult.success("删除用户成功") : AjaxResult.error("删除用户失败");
    }

    @PreAuthorize("hasAuthority('admin')")
    @PostMapping("/authRole")
    @Operation(summary = "分配角色", description = "为用户分配角色，userId和roleId是必要字段,访问权限:admin")
    public AjaxResult insertAuthRole(@org.springframework.web.bind.annotation.RequestBody User user) {
        userService.insertUserAuth(user.getUserId(), user.getRoleIds());
        return AjaxResult.success("分配角色成功");
    }
}